import React, {
  useState,
  useEffect,
  forwardRef,
  useImperativeHandle,
} from "react";
import { Tree, Input, Form } from "antd";
import menuConfig from "../../config/menuConfig";

const { TreeNode } = Tree;

const AddAuth = forwardRef((props, ref) => {
  const { role } = props;
  const [checkedKeys, setCheckedKeys] = useState(role.menus || []);

  useImperativeHandle(ref, () => ({
    getMenus: () => checkedKeys,
  }));

  useEffect(() => {
    setCheckedKeys(role.menus || []);
  }, [role]);

  const onCheck = (checkedKeys) => {
    setCheckedKeys(checkedKeys);
  };

  const renderTreeNodes = (data) =>
    data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} {...item} />;
    });

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 15 },
  };

  return (
    <div>
      <Form.Item label="角色名称" {...formItemLayout}>
        <Input value={role.name} disabled />
      </Form.Item>
      <Tree
        checkable
        onCheck={onCheck}
        checkedKeys={checkedKeys}
        defaultExpandAll
      >
        <TreeNode title="平台权限" key="all">
          {renderTreeNodes(menuConfig)}
        </TreeNode>
      </Tree>
    </div>
  );
});

export default AddAuth;
